import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:provider/provider.dart';
import 'package:shopping_list/common/utils.dart';
import 'package:shopping_list/components/form_text.dart';
import 'package:shopping_list/components/item.dart';
import 'package:shopping_list/components/text_item.dart';
import 'package:shopping_list/components/toast.dart';
import 'package:shopping_list/global.dart';
import 'package:shopping_list/manager/main_manager.dart';
import 'package:shopping_list/pages/home.dart';

class EditPage extends StatefulWidget {
  EditPage({Key key, this.id, this.data}) : super(key: key);
  final data;
  final id;

  @override
  State<StatefulWidget> createState() => _EditPageState();
}

class _EditPageState extends State<EditPage> {
  var _data;

  List _goodsList = [];

  @override
  void initState() {
    setState(() {
      _data = widget.data;
    });

    _goodsList = json.decode(_data['goods']);

    super.initState();
  }

  void removeGoods(int index) {
    setState(() => {_goodsList.removeAt(index)});
  }

  List<Widget> renderGoodsList() {
    List<Widget> goodsWidgetList = [];
    for (int i = 0; i < _goodsList.length; i++) {
      Map goods = _goodsList[i];
      goodsWidgetList.add(
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Expanded(
              child: Container(
                padding: EdgeInsets.all(10),
                margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                decoration: BoxDecoration(
                  color: Global.backgroundColor,
                  borderRadius: BorderRadius.circular(30),
                ),
                child: FormText(
                  maxLine: 1,
                  text: goods['name'],
                  hintText: "请输入需要购买的商品名称",
                  textAlign: TextAlign.start,
                  onChanged: (text) {
                    setState(() {
                      goods['name'] = text;
                    });
                  },
                ),
              ),
            ),
            IconButton(
              icon: Icon(Icons.delete),
              onPressed: () {
                removeGoods(i);
              },
            )
          ],
        ),
      );
    }

    return goodsWidgetList;
  }

  @override
  Widget build(BuildContext context) {
    MainManager _mainManager = Provider.of<MainManager>(context);

    return Scaffold(
      appBar: AppBar(
        iconTheme: IconThemeData(color: Global.backgroundColor),
        toolbarHeight: 50,
        elevation: 0,
        title: Text(
          "${widget.id == '000' ? '添加' : '编辑'}购物清单",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: Global.backgroundColor,
            fontSize: 15,
          ),
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.save),
            tooltip: '保存',
            onPressed: () {
              if (_data['use'] == '') {
                Toast.show(context, msg: '您还没有填写商品用途');
                return;
              }
              if (_data['channel'] == '') {
                Toast.show(context, msg: '您还没有填写购买渠道');
                return;
              }
              if (_goodsList.length == 0) {
                Toast.show(context, msg: '您还没有添加商品');
                return;
              }
              if (_goodsList[0]['name'] == '') {
                Toast.show(context, msg: '您还没有添加商品');
                return;
              }

              _data['goods'] = json.encode(_goodsList);

              if (widget.id == '000') {
                String id = DateTime.now().millisecondsSinceEpoch.toString();
                _mainManager.insert(id, json.encode(_data));
              } else {
                _mainManager.update(widget.id.toString(), json.encode(_data));
              }
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => HomePage(),
                ),
              );
            },
          ),
        ],
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(color: Global.cardBackgroundColor),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                padding: EdgeInsets.all(13),
                child: Text(
                  '清单基本信息',
                  style: TextStyle(
                    color: Global.fontColor.withOpacity(0.8),
                    fontSize: 19,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
              TextItem(
                title: "用途",
                text: _data['use'],
                hintText: "输入物品用途",
                onChanged: (text) {
                  setState(() {
                    _data['use'] = text;
                  });
                },
              ),
              TextItem(
                title: "购买渠道",
                text: _data['channel'],
                hintText: "输入购买渠道",
                onChanged: (text) {
                  setState(() {
                    _data['channel'] = text;
                  });
                },
              ),
              Item(
                title: "购买日期",
                text: _data['date'],
                hintText: "请选择日期",
                onTap: () {
                  DatePicker.showDatePicker(
                    context,
                    pickerTheme: DateTimePickerTheme(confirm: Text('确定')),
                    onMonthChangeStartWithFirstDate: true,
                    minDateTime: DateTime.parse('2020-09-20'),
                    maxDateTime: DateTime.parse('2022-12-31'),
                    initialDateTime: DateTime.now(),
                    dateFormat: 'yyyy-MMMM-dd',
                    locale: DateTimePickerLocale.zh_cn,
                    onConfirm: (dateTime, List<int> index) {
                      setState(() {
                        _data['date'] = dateTime.toString().substring(0, 10);
                      });
                    },
                  );
                },
              ),
              SizedBox(height: 10),
              Container(
                padding: EdgeInsets.all(10),
                width: MediaQuery.of(context).size.width,
                decoration: BoxDecoration(
                  color: Global.backgroundColor,
                  border: Border(
                    bottom: BorderSide(
                      color: Global.fontSecondColor.withOpacity(0.2),
                      width: 1,
                      style: BorderStyle.solid,
                    ),
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text(
                      "备注",
                      style: TextStyle(
                        fontSize: 16,
                        color: Global.fontColor,
                      ),
                    ),
                    SizedBox(height: 5),
                    FormText(
                      maxLine: 4,
                      text: _data['remark'],
                      hintText: "最多50个字（选填）",
                      textAlign: TextAlign.start,
                      onChanged: (text) {
                        setState(() {
                          _data['remark'] = text;
                        });
                      },
                    ),
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.all(13),
                child: Text(
                  '商品',
                  style: TextStyle(
                    color: Global.fontColor.withOpacity(0.8),
                    fontSize: 19,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
              Column(
                children: renderGoodsList(),
              ),
              Center(
                child: InkWell(
                  onTap: () {
                    setState(() {
                      _goodsList.add({'name': '', 'checked': '0'});
                    });
                  },
                  child: Container(
                    width: 120,
                    padding: EdgeInsets.all(7),
                    margin: EdgeInsets.all(18),
                    decoration: BoxDecoration(
                      color: Global.mainColor,
                      border: Border.all(color: Global.mainColor, width: 1),
                      borderRadius: BorderRadius.circular(40),
                    ),
                    child: Center(
                      child: Text(
                        '添加新商品',
                        style: TextStyle(
                          color: Global.backgroundColor,
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
